package com.horay.springbootdemo.caffeine.redis.userinfo.service.impl;

import com.horay.springbootdemo.caffeine.redis.userinfo.service.UserInfoService;
import com.horay.springbootdemo.common.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.Set;

/**
 * 用户信息业务实现类
 *
 * @author heyingcheng
 * @date 2019/12/9 15:21
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public String registerUser(UserInfo userInfo) {
        userInfo.setUserId(System.currentTimeMillis());
        Date now = new Date();
        redisTemplate.opsForHash().put(String.join(":", UserInfo.class.getSimpleName(), String.valueOf(userInfo.getUserId())), "userName", userInfo.getUserName());
        redisTemplate.opsForHash().put(String.join(":", UserInfo.class.getSimpleName(), String.valueOf(userInfo.getUserId())), "userName", userInfo.getUserName());
        jdbcTemplate.update("INSERT INTO user_info (user_id, user_name, user_name_cn, birth, phone, gmt_create, gmt_modified) VALUES (?, ?, ?, ?, ?, ?, ?)", userInfo.getUserId(), userInfo.getUserName(), userInfo.getUserNameCn(), userInfo.getBirth(), userInfo.getPhone(), now, now);
        return "SUCCESS";
    }

    @Override
    public String cacheUser() {
        jdbcTemplate.queryForList(UserInfo.DEFAULT_SELECT_SQL).forEach(row -> {
            String userInfoName = UserInfo.class.getSimpleName();
            String userId = String.valueOf(row.get("user_id"));
            Set<Map.Entry<String, Object>> entries = row.entrySet();
            for (Map.Entry<String, Object> entry : entries) {
                if (UserInfo.COLUMN_USER_ID.equalsIgnoreCase(entry.getKey())) {
                    continue;
                }
                redisTemplate.opsForHash().put(String.join(":", userInfoName, userId), entry.getKey(), String.valueOf(entry.getValue()));
            }
        });
        return null;
    }

}
